/***** Setting *****/
var KernelServicesBase = 'http://221.7.246.92:805/Host/';
var uploadBase = 'http://ueshop.cn:81/'; // 图片和附件服务器地址和端口，如http://www.bedoing.com，本机留空
var jsHostBase = 'http://ueshop.cn:81/uetest/';

var tmpImgUrl         = jsHostBase + 'js/uploader/images/bedoing.com.jpg';
var uploadUrl         = uploadBase + 'index.php?app=system&ctl=uploader&act=add&ajax=1';
var delImgUrl         = uploadBase + 'index.php?app=system&ctl=uploader&act=del&ajax=1';
var setAlbumCoverUrl  = uploadBase + 'index.php?app=system&ctl=uploader&act=setAlbumCover&ajax=1';
var albumImgsUrl      = uploadBase + 'index.php?app=system&ctl=uploader&act=album&ajax=1';
var imgListUrl        = uploadBase + 'index.php?app=system&ctl=uploader&act=list&ajax=1';
var loginUrl          = '/Home/Login?returnUrl=%2FBusinessCenter%2Findex.html';
/***** End Setting *****/


// 包含js
document.write('<script type="text/javascript" src="'+jsHostBase+'js/ajaxf.js"></script>');
document.write('<script type="text/javascript" src="'+jsHostBase+'js/editor/xheditor-zh-cn.min.js"></script>');
// 样式
document.write('<link id="uploader-style" type="text/css" rel="stylesheet" href="'+jsHostBase+'js/uploader/uploader.css" />');

var pageUrl = document.location.href;
var ctx = pageUrl.substr(0, pageUrl.lastIndexOf("/") + 1);

var mouseX = 0;
var mouseY = 0;
$(document).mousemove(function (e) {
    if (e.pageX || e.pageY) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    } else if (e.clientX || e.clientY) {
        mouseX = e.clientX;
        mouseY = e.clientY;
    }
});

function ajaxStatusStart() {
    $('#ajax-loading').remove();
    $('body').append('<div id="ajax-loading"></div>');
    $('#ajax-loading').css('left', (mouseX - 50) + 'px');
    $('#ajax-loading').css('top', (mouseY - 64) + 'px');
}

function ajaxStatusStop() {
    $('#ajax-loading').remove();
}



// 如果没有登录则跳转到登录页面
function isBCVisiable() {
    if (typeof u == 'undefined') {
        alert('错误：需要在' + pageUrl + '的</title>后加入用户中心验证代码\n<script type="text/javascript" src="/Home/GetCurrentMember?isjs=1"></script>');
        return;
    }
    
    if (!u.user || !u.pass) {
        window.location = loginUrl;
    }
}


// 如果是用户中心则需要验证权限
if (ctx.substr(ctx.length - 15, 14) == 'BusinessCenter') {
    isBCVisiable();
}


$(document).ready(function () {
    $.ajaxf.init(jsHostBase+'js/AJAX.swf?' + Math.random());

    $(".note, .msg-list tr").hover(
		function () { $(this).addClass("note-hover"); },
		function () { $(this).removeClass("note-hover"); }
	);

    if (typeof u == 'undefined' || typeof u.user == 'undefined' || typeof u.pass == 'undefined') {
        return;
    }

});

function getServiceUrl(cls, method) {
    return KernelServicesBase + cls + '.svc/' + method
}

/**
* 获取请求GET变量
*/
function getQueryParam(item) {
    var svalue = location.search.match(new RegExp('[\?\&]' + item + '=([^\&]*)(\&?)', 'i'));
    return svalue ? decodeURIComponent(svalue[1]) : '';
}

var editorTools = 'Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Fullscreen,About';

/**
* 重置编辑器的高度
*/
function editorHigher(px) {
    var xheHeight = $('.xheIframeArea').height() + px;
    if (xheHeight > 1200 || xheHeight < 100) return false;
    $('.xheIframeArea').css('height', xheHeight + 'px')
    $('.xheLayout').css('height', 'auto');
}

/**
 *
 */
function json2Reqstr(json) {
	var elements = new Array();
	if(typeof json == 'object') {
		for(var name in json) {
			json[name] = typeof json[name] == 'undefined' ? '' : json[name];
			elements.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(json[name].toString()));
		}
	}
	
	return elements.join('&');
}
/**
* json 转 string,提供ajax POST用
*/
function json2String(json) {
    var s = '';
    for (var k in json) {
        if (s.length > 0) {
            s += ',';
        }
        if (typeof json[k] == 'object') {
            if (k == 'user') {
                s += '"user": ["' + json[k][0] + '", "' + json[k][1] + '"]';
            } else {
                s += '"' + jsonsAddSlashes(k) + '": ' + json2String(json[k]);
            }
        } else {
            s += '"' + jsonsAddSlashes(k) + '": "' + jsonsAddSlashes(json[k]) + '"';
        }
    }

    return '{' + s + '}';
}

function jsonsAddSlashes(string) {
    if (typeof string == 'undefined') {
        return '';
    }

    string = string.replace(/\\/g, '\\\\');  // \
    string = string.replace(/"/g, '\\\"');   // "
    string = string.replace(/\//g, '\\\/');  // /
    //string = string.replace(/\b/g, '\\b');   // \b
    //string = string.replace(/\f/g, '\\f');   // \f
    string = string.replace(/\n/g, '\\n');   // \n
    string = string.replace(/\r/g, '\\r');   // \r
    string = string.replace(/\t/g, '\\t');   // \t
    // \uXXXX

    return string;
}

/**
* 在页面中创建弹出div窗口
* 窗口样式在global样式中
*
* @param width 窗口宽 （默认560）
* @param height 窗口高 （默认410）
*/
function creatPopBox(title, width, height, content, dragable) {
    if (typeof (title) == 'undefined') title = '';
    if (typeof (height) == 'undefined') height = 410;
    if (typeof (width) == 'undefined') width = 560;
    if (typeof (content) == 'undefined') content = '<div class="floor-loading"></div>';

    var popBoxPos = PopBoxPos(width, height);
    $('#pop-box').css('left', popBoxPos.left + 'px');
    $('#pop-box').css('top', popBoxPos.top + 'px');

    $('#pop-box, #pop-box-out').remove();

    var style = ' left:' + popBoxPos.left + 'px;'
	          + ' top:' + popBoxPos.top + 'px;'
			  + ' height:' + ((parseInt(height) == 0) ? 'auto;' : height + 'px;')
			  + ' width:' + width + 'px;';

    var html = '<div id="pop-box-out"></div>'
			 + '<div id="pop-box" style="' + style + '">'
			 + '  <a class="close"></a>'
			 + '  <div class="pop-box-in">'
			 + '    <div class="in-wrap">'
			 + (title == '' ? '' : '<h1 class="pop-title">' + title + '</h1>')
			 + '      <div id="pop-main">' + content + '</div>'
			 + '    </div>'
			 + '  </div>'
			 + '</div>'
    $('body').append(html);

    //dragable('pop-box', '.pop-title');

    $('#pop-box .close').click(function () { $('#pop-box, #pop-box-out').remove(); });

    $(window).resize(function () {
        if ($('#pop-box').height() == null) return;
        var popBoxPos = PopBoxPos(width, height);
        $('#pop-box').css('left', popBoxPos.left + 'px');
        $('#pop-box').css('top', popBoxPos.top + 'px');
    });
    if (typeof dragable != 'undefined') {
        dragable(document.getElementById('pop-box'), '#buttonArea');
    }
}

/**
* 隐藏弹出窗口
*
* @param int time 逐渐隐藏时间 单位为毫秒
*/
var hidePopBoxTO;
function hidePopBox(time) {
    if (typeof time == 'undefined') time = 1000;
    clearTimeout(hidePopBoxTO);
    hidePopBoxTO = setTimeout('removePopBox(' + time + ')', time);

    $('#pop-box-out').fadeOut(time);
    $('#pop-box').fadeOut(time);
}
/**
* 关掉浮动窗口
*/
function removePopBox() {
    $('#pop-box').remove();
    $('#pop-box-out').remove();
}
/**
* 获取浮动窗口层的位置
*/
function PopBoxPos(width, height) {
    var pageWidth = window.innerWidth;
    var pageHeight = window.innerHeight;
    if (typeof pageWidth != "number") {
        if (document.compatMode == "CSS1Compat") {
            pageWidth = document.documentElement.clientWidth;
            pageHeight = document.documentElement.clientHeight;
        } else {
            pageWidth = document.body.clientWidth;
            pageHeight = document.body.clientHeight;
        }
    }

    var top = ((pageHeight - height) / 3) + $(window).scrollTop();
    var left = (pageWidth - width) / 2 + $(window).scrollLeft();

    return { 'left': left, 'top': top };
}

/**
 * 使层可拖动
 * 
 * @param string o 可拖动层的id
 * @param string moveTag 光标显示为可移动的元素， 可用id，类，标签，如#xx、.xx或xx 
 */
function dragable(o, moveTag) {
    if (typeof o == "string") o = document.getElementById(o);

    if (typeof moveTag == "string") {
        moveTag = document.getElementById(moveTag);
        o.onmouseover = function (a) {
            moveTag.style.cursor = 'move';
        }

        o.onmouseout = function (a) {
            moveTag.style.cursor = 'normal';
        }
    }

    o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
    o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
    o.orig_index = o.style.zIndex;    
    
    moveTag.onmousedown = function (a) {
        this.style.zIndex = 10000;
        var d = document;
        if (!a) a = window.event;
        var x = a.clientX + d.body.scrollLeft - o.offsetLeft;
        var y = a.clientY + d.body.scrollTop - o.offsetTop;

        d.ondragstart = "return false;"
        d.onselectstart = "return false;"
        d.onselect = "document.selection.empty();"

        if (o.setCapture) {
            o.setCapture();
        } else if (window.captureEvents) {
            window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
        }

        d.onmousemove = function (a) {
            if (!a) a = window.event;
            $('#' + o.id).css('left', a.clientX + document.body.scrollLeft - x + 'px');
            $('#' + o.id).css('top', a.clientY + document.body.scrollTop - y + 'px');

            o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
            o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
        }

        d.onmouseup = function () {
            if (o.releaseCapture) {
                o.releaseCapture();
            } else if (window.captureEvents) {
                window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
            }

            d.onmousemove = null;
            d.onmouseup = null;
            d.ondragstart = null;
            d.onselectstart = null;
            d.onselect = null;
            o.style.cursor = "normal";
            o.style.zIndex = o.orig_index;
        }
    }

    var orig_scroll = window.onscroll ? window.onscroll : function () { };

    window.onscroll = function () {
        orig_scroll();
        o.style.left = o.orig_x + document.body.scrollLeft;
        o.style.top = o.orig_y + document.body.scrollTop;
    }
}

function divLoadPage(div, url, json) {
    $.ajaxf.ready(function () {
        $(div).html('<div class="floor-loading"></div>');

        $.ajaxf.postText(url, json, function (r) {
            $(div).html(r);
        });

    });
}

function hidePageLoading(id) {
    $('.w').show();

    if (typeof id == 'undefined') {
        id = 'page-loading-div';
    }
    //alert(id);
    $('#' + id).remove();
}

function showPageLoading(id) {
    //$('.w').hide();
    if (typeof id == 'undefined') {
        id = 'page-loading-div';
    }

    $('body').append('<div id="' + id + '" class="page-loading floor-loading"></div>');
    var code = "hidePageLoading('" + id + "')";
    //alert(code);
    setTimeout(code, 8000);
}


/**
* 设置cookie
* 
* @param string name
* @param string value
* @param Day expireDays 多少天后过期
*/
function setCookie(name, value, expireDays) {
    var exp = '';

    if (expireDays != null) {
        var exDate = new Date();
        exDate.setDate(exDate.getDate() + expireDays);
        exp = ";expires=" + exDate.toGMTString();
    }

    document.cookie = name + "=" + escape(value) + exp + "; path=/";
}

/**
* 读取cookie
*
* @param string name
*/
function getCookie(name) {
    if (document.cookie.length > 0) {
        start = document.cookie.indexOf(name + "=");
        if (start != -1) {
            start = start + name.length + 1;
            end = document.cookie.indexOf(";", start);
            if (end == -1) end = document.cookie.length;

            return unescape(document.cookie.substring(start, end));
        }
    }

    return "";
}

/**
* 删除cookie
*
* @param string name
*/
function delCookie(name) {
    setCookie(name, "", -1);
}

/**
* 显示提示信息，过hideTime秒钟后消失
* 
* @param string content 内容
* @param string title 标题
* @param int width 提示框宽（可选）
* @param int height 提示框高（可选）
* @param int hideTime 提示框过多少秒后隐藏（可选）
*/
var showMsgTO;
function showMsg(content, title, width, height, hideTime) {

    if (typeof title == 'undefined') title = '提示信息';
    if (typeof width == 'undefined') width = 210;
    if (typeof height == 'undefined') height = 100;
    if (typeof hideTime == 'undefined') hideTime = 3;

    clearTimeout(showMsgTO);
    showMsgTO = setTimeout('hidePopBox()', hideTime * 1000);

    content = '<div class="show-message">' + content + '</div>';
    creatPopBox(title, width, height, content, false);
}

// 生成 UUID
function makeGuid() {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + Math.random().toString(16).substr(2, 12);
}

function getDateTime() {
    var date = new Date();
    return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDay() + ' ' + date.getHours() + ':' + date.getSeconds() + ':' + date.getMinutes();
}



// 图片上传支持js
document.write('<script type="text/javascript" src="'+jsHostBase+'js/uploader/swfupload.js"></script>');
document.write('<script type="text/javascript" src="'+jsHostBase+'js/uploader/lang/zh-cn.js"></script>');
document.write('<script type="text/javascript" src="'+jsHostBase+'js/uploader/uploader.js"></script>');

/**
 * 必多盈文本编辑器
 */
var bdEditor = new function () {
    /**
    * 图片管理插件
    */
    var editorPlugins = {
        btnImg: {
            c: 'xheIcon xheBtnImg',
            t: '插入图片',
            h: 0,
            e: function () {
                var _this = this;
                _this.params = _this.settings.img_upload_params;
                var html = '';  // 图片库显示框架
                html += '<div id="bd-uploader">'
                      + '	<div class="flash" id="fsUploadProgress"></div>'
                      + '   <div id="buttonArea">'
                      + '       <input class="fl" type="checkbox" name="select-all-pic" id="select-all-pic" />'
                      + '       <a href="javascript:void(0);" id="get-pics" class="up-btn fl" title="点击这里把选中的图片插入到编辑器中"><span><div id="div-get-pics">引用图片</div></span></a>'
                      + '       <a href="javascript:void(0);" id="del-pics" class="up-btn fl" title="点击这里批量删除图片"><span><div id="div-del-pics">删除图片</div></span></a>'
                      + '       <a href="javascript:void(0);" id="addFiles" class="up-btn fl" title="点击这里上传图片"><span><div id="divAddFiles">添加文件</div></span></a>'
                      + '   </div>'
                      + '   <div id="photo-list">'
                      + '       <span class="fl note" style="padding:0 0 0 10px;">1.双击图片把该图片插入编辑器； 2.单击选中图片后点击"引用图片"把选中的图片插入编辑器中。 </span>'
                      + '       <ul><div class="floor-loading"></div></ul>'
                      + '   </div>'
                      + '   <div id="photo-paging">'
                      + '     <a href="#" onclick="load();return false;">头页</a>'
                      + '     <a href="#" onclick="load();return false;">上一页</a>'
                      + '     <a href="#" onclick="load();return false;">1</a>'
                      + '     <a href="#" onclick="load();return false;">2</a>'
                      + '     <a href="#" onclick="load();return false;">3</a>'
                      + '     <a href="#" onclick="load();return false;">4</a>'
                      + '     <a href="#" onclick="load();return false;">下一页</a>'
                      + '     <a href="#" onclick="load();return false;">尾页</a>'
                      + '   </div>'
                      + '</div>';

                creatPopBox('', 685, 420, html);

                // 上传图片成功后处理返回数据
                _this.uploadFinishHandler = function (file, r) {
                    try {
                        eval('var r = ' + r);
                    } catch (e) {
                        alert(r);
                    }
					
					$('#no-upload-pic').remove();

                    //alert(r.title);
                    html = '<li class="checked" id="photo-list-item-' + r.img_id + '">'
						 + '  <input type="checkbox" value="' + r.img + '" id="' + r.img_id + '" name="check-pic[' + r.img_id + ']" class="check-pic" checked="checked" />'
						 + '  <p><img class="pic" src="' + r['thumb'] + '" width="98" height="98" ></p>'
						 + '  <p id="checked-pic-title-' + r.img_id + '" class="pic-title">' + r['title'] + '</p>'
						 + '</li>';
                    $('#photo-list ul').prepend(html);

                    // 点击图片选中和去掉选中
                    $('#photo-list li').unbind();
                    $('#photo-list li').click(function () {
                        if ($(this).hasClass('checked')) {
                            $(this).find('.check-pic').removeAttr('checked');
                            $(this).removeClass('checked');
                        } else {
                            $(this).find('.check-pic').attr('checked', 'checked');
                            $(this).addClass('checked');
                        }
                    });

                    // 双击图片插入编辑框
                    $('#photo-list img').unbind();
                    $('#photo-list img').dblclick(function () {
                        var parent = $(this).parent().parent();
                        var src = parent.find('.check-pic').val();
                        var title = parent.find('.pic-title').text();
                        _this.pasteHTML('<img src="' + src + '" alt="' + title + '" />');
                        removePopBox();
                    });
                }


                var editorSwfu;
                //$(function() {
                var settings = {
                    flash_url: jsHostBase+'js/uploader/swfupload.swf',
                    upload_url: uploadUrl + ((uploadUrl.indexOf('?') == -1) ? '?' : '&') + json2Reqstr(_this.params),
                    post_params: { "param name": "param value" }, // json格式
                    file_size_limit: "500 K",
                    file_types: "*.jpg;*.gif;*.png",
                    file_types_description: "图片",
                    file_upload_limit: 12,
                    file_queue_limit: 0,
                    custom_settings: { progressTarget: "fsUploadProgress" },
					file_post_name : "file",

                    debug: false,

                    // Button settings
                    button_image_url: jsHostBase+"js/uploader/images/add.gif",
                    button_width: 80,
                    button_height: 17,
                    button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
                    button_cursor: SWFUpload.CURSOR.HAND,
                    button_placeholder_id: "divAddFiles",
                    button_text: '<span class="theFont">上传图片</span>',
                    button_text_style: ".theFont {color:#006699; }",
                    button_text_left_padding: 20,
                    button_text_top_padding: 0,

                    // The event handler functions are defined in handlers.js
                    file_queued_handler: fileQueued,
                    file_queue_error_handler: fileQueueError,
                    file_dialog_complete_handler: fileDialogComplete,
                    upload_start_handler: uploadStart,
                    upload_progress_handler: uploadProgress,
                    upload_error_handler: uploadError,
                    upload_success_handler: _this.uploadFinishHandler,
                    upload_complete_handler: uploadComplete,
                    queue_complete_handler: queueComplete
                };
                
				//alert(settings.upload_url);
				
				editorSwfu = new SWFUpload(settings);
				
				
                //});

                _this.pageSize = 24;
                _this.page = 0;
                _this.pages = 0;
                _this.pagingFirst = 0;
                _this.pagingLast = 0;
                _this.pagingPre = 0;
                _this.pagingNext = 0;
                _this.json = null;

                /**
                * 显示分页导航条
                */
                _this.showPaging = function () {
                    var paging = '';
                    var r = _this.json;
                    _this.pages = r.totals == 0 ? 0 : Math.ceil(parseInt(r.totals) / _this.pageSize); // 总页数

                    if (_this.page < 0) _this.page = 0;  // 页码从0开始
                    if (_this.page > _this.pages) _this.page = _this.pages;

                    _this.pagingFirst = _this.page - 5; // 第一页
                    _this.pagingLast = _this.page + 5;  // 最后一页
                    _this.pagingPre = _this.page - 1;   // 上一页
                    _this.pagingNext = _this.page + 1;  // 下一页

                    if (_this.pagingFirst < 0) _this.pagingFirst = 0;
                    if (_this.pagingPre < 0) _this.pagingPre = 0;
                    if (_this.pagingLast >= _this.pages) _this.pagingLast = _this.pages - 1;
                    if (_this.pagingNext >= _this.pages) _this.pagingNext = _this.pages - 1;

                    paging += "<a href=\"javascript:;\" page=\"0\">[首页]</a>";
                    paging += "<a href=\"javascript:;\" page=\"" + _this.pagingPre + "\">[上一页]</a>";

                    for (var i = _this.pagingFirst; i <= _this.pagingLast; i++) {
                        var current = '';
                        if (i == _this.page) current = 'class="current"';
                        paging += "<a href=\"javascript:;\" page=\"" + i + "\" " + current + ">[" + (i + 1) + "]</a>";
                        current = '';
                    }

                    paging += "<a href=\"javascript:;\" page=\"" + _this.pagingNext + "\">[下一页]</a>";
                    paging += "<a href=\"javascript:;\" page=\"" + (_this.pages - 1) + "\">[尾页]</a>";
                    paging += ' 共' + _this.pages + '页,' + r.totals + '张';

                    $('#photo-paging').html(paging);

                    $('#photo-paging a').unbind();
                    $('#photo-paging a').click(function () { _this.loadPage($(this).attr('page')); });
                }


                /**
                * 显示已上传的图片列表
                */
                _this.showPhotos = function () {
                    var r = _this.json;
					
                    if (r.err) {
                        // 没有权限则转到登录页
                        if ('denned' == r.err) {
                            parent.window.location = ''; // 转到登录页
                            return;
                        }

                        // 显示错误信息
                        $('#photo-list ul').html('<p class="err">' + r.err + '</p>');
                        return;
                    }

                    var html = '';
                    var images = r.images;
                    if (images.length <= 0) {
						$('#photo-list ul').html('<p id="no-upload-pic">您还没有上传图片！</p>');
                    } else {
                        html = '';
                        for (var i in images) {
                            html += '<li id="photo-list-item-' + images[i]['img_id'] + '">'
								  + '  <input class="check-pic" type="checkbox" name="check-pic[' + images[i]['img_id'] + ']" id="' + images[i]['img_id'] + '" value="' + images[i]['img'] + '" />'
								  + '  <p><img class="pic" src="' + images[i]['thumb'] + '" ></p>'
								  + '  <p id="checked-pic-title-' + images[i]['img_id'] + '" class="pic-title">' + images[i]['title'] + '</p>'
								  + '</li>';
                        }

                        $('#photo-list ul').html(html);
                    }

                    //alert(html);

                    // 点击图片选中和去掉选中
                    $('#photo-list li').click(function () {
                        if ($(this).hasClass('checked')) {
                            $(this).find('.check-pic').removeAttr('checked');
                            $(this).removeClass('checked');
                        } else {
                            $(this).find('.check-pic').attr('checked', 'checked');
                            $(this).addClass('checked');
                        }
                    });

                    // 双击图片插入编辑框
                    $('#photo-list img').dblclick(function () {
                        var parent = $(this).parent().parent();
                        var src = parent.find('.check-pic').val();
                        var title = parent.find('.pic-title').text();
                        _this.pasteHTML('<img src="' + src + '" alt="' + title + '" />');
                        removePopBox();
                    });

                    // 选中或去掉所有选择的图片
                    $('#bd-uploader #select-all-pic').click(function () {
                        if (!$(this).attr('checked')) {
                            $('#photo-list input.check-pic').removeAttr('checked')
                            $('#photo-list li').removeClass('checked')
                        } else {
                            $('#photo-list input.check-pic').attr('checked', 'checked')
                            $('#photo-list li').addClass('checked')
                        }
                    });

                    // 删除图片
                    $('#del-pics').click(function () {
                        var pics = new Array();
                        var picsData = new Array();
                        var obj = $('#photo-list input.check-pic:checked');
                        if (obj.length <= 0) {
                            alert('请选择图片');
                            return;
                        }
						
                        if (!confirm('您确定要删除选中的图片吗？')) {
                            return false;
                        }

                        for (var i = 0; i < obj.length; i++) {
                            pics.push(obj[i].id);
                            picsData.push('imgs_id=' + obj[i].id);
                        }

                        $.ajaxf.post(delImgUrl, picsData.join('&'), function (r) {
                            try {
                                eval('var r=' + r);
                                if (typeof r == 'object' && r.err.length == 0) {
                                    _this.loadPage(_this.page);
                                }
                            } catch (e) {
                                alert(r);
                            }

                        }, 'form');
                    });

                    // 批量引用图片
                    $('#get-pics').click(function () {
                        var obj = $('#photo-list input.check-pic:checked');
                        if (obj.length <= 0) {
                            alert('请选择图片');
                            return;
                        }

                        var html = '';
                        for (var i = 0; i < obj.length; i++) {
                            html += '<img src="' + obj[i].value + '" alt="' + $('#checked-pic-title-' + obj[i].id).text() + '" /><br />';
                        }

                        _this.pasteHTML(html);
                        removePopBox();
                    });
                }

                /**
                * 加载图片库
                *
                * @param int page 页码
                * @param int pageSize 每页记录数
                */
                _this.loadPage = function (page) {
                    _this.page = parseInt(page);

                    // 解除绑定元素
                    $('#select-all-pic').removeAttr('checked');
                    $('#photo-list li').unbind();
                    $('#photo-list img').unbind();
                    $('#bd-uploader #select-all-pic').unbind();
                    $('#del-pics').unbind();
                    $('#get-pics').unbind();

                    $('#photo-list ul').html('<div class="floor-loading"></div>');
                    $.ajaxf.getJSON(imgListUrl, 'page=' + _this.page + '&pageSize=' + _this.pageSize + '&ent_id=' + _this.params.ent_id + '&pid=' + _this.params.pid + '&rand='+Math.random(), function (r) {
						alert(typeof r);
						if(typeof r === 'string') {
							alert('服务器端出错');
							return false;
						}
						_this.json = r;
                        _this.showPaging();
                        _this.showPhotos();
                        r = null;
                    });
                }

                // 载入完成后
                $.ajaxf.ready(function () {
                    _this.loadPage(0);
                });
            }
        }
    }
    // End 图片管理插件

    this.apply = function (id, params) {

        var opts = {
            img_upload_params: { ent_id: '', pid: '' },
            skin: 'o2007blue',
            plugins: editorPlugins,
            tools: 'Pastetext,|,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,Removeformat,|,Align,List,Indent,Outdent,|,Link,Unlink,btnImg,map,Table,|,Source,|,About'
        };
		
        // 传参给 上传插件
        if (typeof params != undefined) {
            for (var i in params) {
                opts.img_upload_params[i] = params[i];
            }
        }
		
		try {
		    return $(id).xheditor(opts);
		} catch (e) {
			alert(e);
		}
    }
}

